﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Rung.Soft.Jx3Tookit.Addon.AutoPress.Utility;

namespace Rung.Soft.Jx3Tookit.Addon.AutoPress.Business
{
    /// <summary>
    /// 工作任务类。
    /// 具体定义了一次任务需要完成的按键规则。
    /// </summary>
    [Serializable]
    public class SkillTasker
    {
        public bool IsBusy = false;

        public List<SkillAction> Action;

        public SkillTasker()
        {
            this.Action = new List<SkillAction>(10);
        }

        public void Start()
        {
            if (this.IsBusy) return;

            this.IsBusy = true;
            if (this.OnTaskStart != null) this.OnTaskStart();

            foreach (SkillAction a in Action)
            {
                //if (this.OnStart != null) this.OnStart(string.Format("<{0}>{1}{2}", a.Type, a.Key, a.Delay));

                if (this.IsBusy)
                {
                    if (a.Type == ActionType.Delay)
                    {
                        this.Sleep(a.Delay);
                    }
                    else if (a.Type == ActionType.Key)
                    {
                        this.KeyClick(a.Key.Key);
                    }
                }
            }

            this.IsBusy = false;
            if (this.OnTaskFinish != null) this.OnTaskFinish();
        }

        private void KeyClick(Keys key)
        {
            this.KeyClick((byte)key);
        }

        private void KeyClick(byte key)
        {
            Win32API.keybd_event(key, 0, 0, 0); //112为f1的ascii码值
            System.Threading.Thread.Sleep(10);
            Win32API.keybd_event(key, 0, 2, 0); //112为f1的ascii码值
        }

        public void Sleep(int msecond)
        {
            DateTime time = DateTime.Now;
            while (time != DateTime.MinValue && time.AddMilliseconds(msecond) > DateTime.Now)
            {
                System.Threading.Thread.Sleep(10);
            }
        }

        public void Stop()
        {
            this.IsBusy = false;
        }

        [NonSerialized]
        public StartEndEvent OnTaskStart;
        [NonSerialized]
        public StartEndEvent OnTaskFinish;
    }
    public delegate void StartEndEvent();
}
